package com.touch.app.service.impl;

import com.alibaba.fastjson.JSON;
import com.touch.app.common.domain.*;
import com.touch.app.common.util.ChatGPT;
import com.touch.app.common.util.HttpUtils;
import com.touch.app.service.ChatGPTService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Slf4j
@Service
public class ChatGPTServiceImpl implements ChatGPTService {

    @Value("${openai.url}")
    private String URL;

    @Value("${openai.token}")
    private String TOKEN;

    @Override
    public ChatGPTResponse askQuestion(Ask ask) {
        ChatGPT gpt = new ChatGPT(TOKEN, URL);
        String response = gpt.ask(ask);
        ChatGPTResponse chatGPTResponse = null;
        try {
            chatGPTResponse = JSON.parseObject(response, ChatGPTResponse.class);
        }catch (Exception e) {
            log.error("JSON parse Http response error, response is:\n{}\nerror message is {}", response, e.getMessage());
        }
        return chatGPTResponse;
    }

    @Override
    public ChatGPTResponse request(ChatGPTRequest chatGPTRequest, HttpServletRequest request) {
        Enumeration<String> headerNames = request.getHeaderNames();
        Map<String, String> headers = new HashMap<>();
        if (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            if (StringUtils.hasLength(headerName)) {
                String headerValue = request.getHeader(headerName);
                headers.put(headerName, headerValue);
            }
        }
        headers = checkHeader(headers);
        String response = HttpUtils.post(URL, headers, JSON.toJSONString(chatGPTRequest));
        ChatGPTResponse chatGPTResponse;
        try {
            chatGPTResponse = JSON.parseObject(response, ChatGPTResponse.class);
        }catch (Exception e) {
            String errorMessage = "JSON parse Http response error, response is: [ " + response + "] error message is [" + e.getMessage() + "]";
            log.error(errorMessage);
            chatGPTResponse = new ChatGPTResponse();
            chatGPTResponse.setId(TOKEN);
            chatGPTResponse.setModel(chatGPTRequest.getModel());
            chatGPTResponse.setCreated(new Date().getTime());
            Choices choices = new Choices();
            ChatGPTMessage message = new ChatGPTMessage();
            message.setContent(errorMessage);
            message.setRole("assistant");
            choices.setMessage(message);
            List<Choices> choicesList = new LinkedList<>();
            choicesList.add(choices);
            chatGPTResponse.setChoices(choicesList);
        }
        return chatGPTResponse;
    }

    private Map<String, String> checkHeader(Map<String, String> headers) {
        if (headers == null || headers.isEmpty()) {
            headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Authorization", "Bearer " + TOKEN);
        }else {
            String contentType = headers.get("Content-Type");
            String auth = headers.get("Authorization");
            if (StringUtils.hasLength(contentType)) {
                headers.put("Content-Type", "application/json");
            }
            if (StringUtils.hasLength(auth)) {
                headers.put("Authorization", "Bearer " + TOKEN);
            }
        }
        return headers;
    }
}
